package visual

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/assets/cgs_portal"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"net/http"
	"strings"
	"time"
)

func init() {
	// 复制应用的功能弃用
	server.Handle(http.MethodPost, "/api/Cgs/Portal/Visual/Copy", Copy, server.Login)
}

func Copy(w http.ResponseWriter, r *http.Request) {
	// 根据 id 复制视图， 类型
	_ = r.ParseForm()

	visualType := strings.TrimSpace(r.FormValue("VisualType"))

	if visualType == "" {
		_, _ = helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "VisualType is not allowed empty!",
		})
		return
	}
	if _, ok := cgs_portal.VisualTypes[visualType]; !ok {
		_, _ = helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "VisualType is not existed.",
		})
		return
	}

	// id
	visualId, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("ID")))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "ID is not allowed to be empty.",
		})
		return
	}


	// 集合名
	visualCollectionName := server.CgsPortalVisualCollectionName + visualType
	visualConfigCollectionName := server.CgsPortalVisualCollectionName + visualType + "Config"

	db, err := server.Mongo()
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}

	filter := bson.M{
		"ID": visualId,
	}
	doc := bson.M{}
	find, _ := db.FindOne(visualCollectionName, filter, &doc)

	if !find {
		_, _ = helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "The visual is not existed.",
		})
		return
	}

	if server.Config.Authority.Enabled {
		user, _ := server.GetCurrentUser(r)

		if user == nil {
			_, _ = helper.WriteJSON(w, server.Result{
				Code: 300,
				Msg:  "Permission denied.",
			})
			return
		}

		// save other people's scene
		if doc["UserID"] != nil && doc["UserID"].(string) != user.ID {
			_, _ = helper.WriteJSON(w, server.Result{
				Code: 300,
				Msg:  "Permission denied.",
			})
			return
		}

		// not admin save scene without UserID
		if doc["UserID"] == nil && user.RoleName != "Administrator" {
			_, _ = helper.WriteJSON(w, server.Result{
				Code: 300,
				Msg:  "Permission denied.",
			})
			return
		}
	}


	newVisualId := primitive.NewObjectID()
	newConfigId := primitive.NewObjectID()

	visualDoc := bson.M{
		"ID":			newVisualId,
		"Password":		doc["Password"],
		"Category":		doc["Category"],
		"Status":		doc["Status"],
		"Title":		doc["Title"],
		"CreateTime":	time.Now(),
		"UpdateTime":	time.Now(),
	}
	if doc["BackgroundUrl"] != nil && doc["BackgroundUrl"] != "" {
		visualDoc["BackgroundUrl"] = doc["BackgroundUrl"]
	}

	if doc["UserID"] != nil {
		visualDoc["UserID"] = doc["UserID"]
	}

	_, _ = db.InsertOne(visualCollectionName, visualDoc)


	filter = bson.M{
		"VisualId": visualId,
	}
	doc = bson.M{}
	// 查找config
	find, _ = db.FindOne(visualConfigCollectionName, filter, &doc)

	if !find {
		_, _ = helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "The visual config is not existed.",
		})
		return
	}

	configDoc := bson.M{
		"ID":			newConfigId,
		"VisualId":		newVisualId,
		"Detail":		doc["Detail"],
		"Component":	doc["Component"],
	}

	if doc["SceneUrl"] != nil && doc["SceneUrl"] != "" {
		configDoc["SceneUrl"] = doc["SceneUrl"]
	}
	if doc["UserID"] != nil {
		configDoc["UserID"] = doc["UserID"]
	}

	_, _ = db.InsertOne(visualConfigCollectionName, configDoc)

	result := copyResult{}
	result.Code = 200
	result.Msg = "Copy successfully!"
	result.ID = newVisualId.Hex()

	_, _ = helper.WriteJSON(w, result)

}

type copyResult struct {
	server.Result
	ID string
}